package com.hxut.common.exception;

import com.hxut.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * description: GlobalExceptionHandler
 * date: 2022/6/21 11:35
 * author: MR.孙
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @description:  实体类校验异常
     * @param e
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 21:16
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        log.error("实体类校验异常：-------------{}",objectError.getDefaultMessage());
        return Result.fail(objectError.getDefaultMessage());
    }




    /**
    * @param e 异常类参数
    *@description: 运行时错误
    *@return: com.hxut.co拦截方法mmon.lang.Result
    *@author: MR.孙
    *@date: 2022/6/21 12:26
    **/
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("运行时异常：-------------{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
    
    /**
    * @param e 异常类参数
    *@description: 非法参数异常
    *@return: com.hxut.common.lang.Result
    *@author: MR.孙
    *@date: 2022/6/21 12:34
    **/
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        log.error("Assert异常：-------------{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
}
